<template>
    <div
        class="fishing-grounds-root"
        :class="{ 'has-custom-range': selectedTime === 'custom' }"
        style="width: 100%; height: 100%; position: relative; display: flex;"
    >
        <!-- 左侧竖排图例 -->
        <div class="legend-container">
            <div 
                v-for="(item, index) in currentLegendData" 
                :key="index"
                class="legend-item"
            >
                <span 
                    class="legend-color"
                    :style="{ backgroundColor: item.color }"
                ></span>
                <span class="legend-text">{{ item.name }}</span>
            </div>
        </div>
        
        <!-- 图表区域 -->
        <div ref="chartContainer" class="chart-container"></div>
        
        <!-- 时间选择器 -->
        <div class="time-selector">
            <label 
                v-for="option in timeOptions" 
                :key="option.value"
                class="radio-label"
                :class="{ active: selectedTime === option.value }"
            >
                <input 
                    type="radio" 
                    :value="option.value" 
                    v-model="selectedTime"
                    @change="handleTimeChange"
                    class="radio-input"
                />
                <span class="radio-text">{{ option.label }}</span>
            </label>
        </div>
        <div
            v-if="selectedTime === 'custom'"
            class="custom-date-range"
        >
            <input
                type="date"
                v-model="customDateRange.startDate"
                @change="onCustomDateChange"
                class="date-input"
                placeholder="开始日期"
            />
            <span class="date-separator">至</span>
            <input
                type="date"
                v-model="customDateRange.endDate"
                @change="onCustomDateChange"
                class="date-input"
                placeholder="结束日期"
            />
        </div>
    </div>
</template>

<script>
import 'echarts-gl'
import { createChartOption } from './option.js'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
    props: {
        Data: {
            type: Array,
            required: false
        }
    },
    data() { 
        return {
            chartInstance2: null,
            resizeObserver: null,
            optionsData: [],
            loading: false,
            error: null,
            selectedTime: 'week', // week, month, year
            timeOptions: [
                { label: '近一周', value: 'week' },
                { label: '近一月', value: 'month' },
                { label: '近一年', value: 'year' },
                { label: '自定义', value: 'custom' }
            ],
            customDateRange: {
                startDate: '',
                endDate: ''
            },
            customData: [],
            mockData: {
                week: [
                    { name: '印度洋公海渔场', value: 3200, itemStyle: { color: 'rgba(79,191,227,1)' } },
                    { name: '北太平洋公海渔场', value: 2800, itemStyle: { color: 'rgba(249,170,114,1)' } },
                    { name: '东南太平洋公海渔场', value: 3500, itemStyle: { color: 'rgba(179,229,251,1)' } },
                    { name: '西南大西洋公海渔场', value: 2100, itemStyle: { color: 'rgba(250,210,95,1)' } }
                ],
                month: [
                    { name: '印度洋公海渔场', value: 12500, itemStyle: { color: 'rgba(79,191,227,1)' } },
                    { name: '北太平洋公海渔场', value: 11200, itemStyle: { color: 'rgba(249,170,114,1)' } },
                    { name: '东南太平洋公海渔场', value: 13800, itemStyle: { color: 'rgba(179,229,251,1)' } },
                    { name: '西南大西洋公海渔场', value: 9800, itemStyle: { color: 'rgba(250,210,95,1)' } }
                ],
                year: [
                    { name: '印度洋公海渔场', value: 156000, itemStyle: { color: 'rgba(79,191,227,1)' } },
                    { name: '北太平洋公海渔场', value: 142000, itemStyle: { color: 'rgba(249,170,114,1)' } },
                    { name: '东南太平洋公海渔场', value: 168000, itemStyle: { color: 'rgba(179,229,251,1)' } },
                    { name: '西南大西洋公海渔场', value: 118000, itemStyle: { color: 'rgba(250,210,95,1)' } }
                ]
            }
        };
    },
    computed: {
        currentLegendData() {
            // 根据当前选择的时间段获取图例数据
            let data = [];
            if (this.selectedTime === 'custom') {
                data = this.customData;
            } else if (this.Data && this.Data.length > 0) {
                data = this.Data;
            } else {
                data = this.mockData[this.selectedTime] || this.mockData.week;
            }
            return data.map(item => ({
                name: item.name,
                color: item.itemStyle.color
            }));
        }
    },
    watch: {
        Data: {
            handler(newData) {
                if (newData && newData.length > 0) {
                    this.updateData(newData);
                }
            },
            deep: true,
            immediate: true
        }
    },
    mounted() {
        this.initChart();
        this.updateChart();
    },
    methods: {
        initChart() {
            if (this.$refs.chartContainer) {
                this.chartInstance2 = echarts.init(this.$refs.chartContainer, this.$echartsConfig.theme);
                this.resizeObserver = new ResizeObserver(() => {
                    this.chartInstance2 && this.chartInstance2.resize();
                });
                this.resizeObserver.observe(this.$refs.chartContainer);
            }
        },
        updateChart() {
            if (!this.chartInstance2) return;

            let sourceData = [];
            
            if (this.selectedTime === 'custom') {
                sourceData = this.customData;
            } else if (this.Data && this.Data.length > 0) {
                this.optionsData = this.Data;
                sourceData = this.optionsData;
            } else {
                sourceData = this.mockData[this.selectedTime] || this.mockData.week;
            }

            if (!sourceData || sourceData.length === 0) {
                this.chartInstance2.clear();
                return;
            }

            this.optionsData = sourceData;
            const option = createChartOption(this.optionsData);
            this.chartInstance2.setOption(option, true);
        },
        updateData(newData) {
            this.optionsData = newData;
            this.updateChart();
        },
        handleTimeChange() {
            if (this.selectedTime === 'custom') {
                if (this.customDateRange.startDate && this.customDateRange.endDate) {
                    this.generateCustomData();
                } else if (this.chartInstance2) {
                    this.customData = [];
                    this.chartInstance2.clear();
                }
            } else {
                this.updateChart();
            }
        },
        onCustomDateChange() {
            if (this.selectedTime !== 'custom') return;
            if (this.customDateRange.startDate && this.customDateRange.endDate) {
                this.generateCustomData();
            }
        },
        generateCustomData() {
            const { startDate, endDate } = this.customDateRange;
            const start = new Date(startDate);
            const end = new Date(endDate);

            if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
                return;
            }
            if (start > end) {
                return;
            }

            const dayMilliseconds = 1000 * 60 * 60 * 24;
            const daysDiff = Math.floor((end - start) / dayMilliseconds) + 1;

            if (daysDiff <= 0) {
                return;
            }

            const referenceData = (this.Data && this.Data.length > 0)
                ? this.Data
                : (this.mockData.week || []);

            if (!referenceData || referenceData.length === 0) {
                return;
            }

            const min = Math.max(60, daysDiff * 35);
            const max = Math.min(180000, daysDiff * 210);

            this.customData = referenceData.map(item => ({
                name: item.name,
                value: Math.floor(Math.random() * (max - min + 1) + min),
                itemStyle: {
                    color: item.itemStyle?.color || item.color || '#5CA0B1'
                }
            }));

            this.updateChart();
        }
    },
    beforeDestroy() {
        if (this.chartInstance2) {
            this.chartInstance2.dispose();
        }
        if (this.resizeObserver && this.$refs.chartContainer) {
            this.resizeObserver.unobserve(this.$refs.chartContainer);
            this.resizeObserver.disconnect();
        }
    }
};
</script>

<style scoped lang="less">
.legend-container {
    width: 120px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    padding: 10px 15px;
    box-sizing: border-box;
    flex-shrink: 0;

    .legend-item {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        width: 100%;

        &:last-child {
            margin-bottom: 0;
        }

        .legend-color {
            display: inline-block;
            width: 15px;
            height: 8px;
            border-radius: 2px;
            margin-right: 8px;
            flex-shrink: 0;
        }

        .legend-text {
            color: #fff;
            font-size: 11px;
            white-space: nowrap;
            flex: 1;
        }
    }
}

.chart-container {
    flex: 1;
    height: 100%;
    position: relative;
}

.time-selector {
    position: absolute;
    top: 5px;
    right: 5px;
    z-index: 10;
    display: flex;
    gap: 8px;
    padding: 4px;
    background: rgba(0, 0, 0, 0.4);
    border-radius: 4px;
    pointer-events: auto;

    .radio-label {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 3px 6px;
        border-radius: 3px;
        transition: all 0.3s;
        color: rgba(255, 255, 255, 0.7);
        font-size: 11px;
        white-space: nowrap;

        &.active {
            background: rgba(79, 191, 227, 0.6);
            color: #fff;
        }

        &:hover {
            background: rgba(79, 191, 227, 0.4);
            color: #fff;
        }

        .radio-input {
            display: none;
        }

        .radio-text {
            user-select: none;
        }
    }
}

.custom-date-range {
    position: absolute;
    top: 42px;
    right: 5px;
    z-index: 9;
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 6px;
    background: rgba(0, 0, 0, 0.32);
    border-radius: 4px;
    pointer-events: auto;
}

.date-input {
    padding: 0.3rem 0.6rem;
    background: rgba(12, 30, 60, 0.55);
    border: 1px solid rgba(79, 191, 227, 0.45);
    border-radius: 3px;
    color: #FFFFFF;
    font-size: 10px;
    outline: none;
    transition: all 0.3s ease;
}

.date-input:hover,
.date-input:focus {
    border-color: rgba(79, 191, 227, 0.8);
    background: rgba(12, 30, 60, 0.75);
}

.date-separator {
    color: rgba(255, 255, 255, 0.75);
    font-size: 10px;
    user-select: none;
}

.date-input::-webkit-calendar-picker-indicator {
    filter: invert(1);
    cursor: pointer;
}
</style>

